package demo.socket;

import java.awt.Button;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpPicClient {
	private Socket s;
	private Frame f;
	private Button b;
	private FileDialog fd;
	private File file;
	private TextArea ta;

	public TcpPicClient() throws UnknownHostException, IOException {
		init();
	}

	public void send() throws FileNotFoundException, IOException {
		if (!file.exists()) {
			ta.append("��ѡ��ͼƬ\n");
			return;
		}
		if (!file.getName().endsWith(".jpg")) {
			ta.append("��ʽ����ȷ��������ѡ��\n");
			return;
		}
		if (file.length() > 1024 * 1204 * 20) {
			ta.append("�ļ����󣬲�֧���ϴ�\n");
			return;
		}
		s = new Socket(InetAddress.getLocalHost(), 10000);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = bis.read(buf)) != -1) {
			bos.write(buf, 0, len);
			bos.flush();
		}
		s.shutdownOutput();
		bis.close();
		byte[] bb = new byte[1024];
		int num = s.getInputStream().read(bb);
		ta.append("ͼƬ:" + file.getName() + new String(bb, 0, num) + "\n");
		s.close();
	}

	public void init() throws IOException, UnknownHostException {
		f = new Frame("����ͼƬ");
		f.setBounds(600, 500, 500, 400);
		f.setLayout(new FlowLayout());
		b = new Button("��");
		fd = new FileDialog(f);
		b.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fd.setVisible(true);
				file = new File(fd.getDirectory() + fd.getFile());
				try {
					send();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		ta = new TextArea(20, 60);
		f.add(b);
		f.add(ta);
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		f.setVisible(true);
	}

	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO �Զ����ɵķ������
		new TcpPicClient();
	}

}
